import * as createCustomerService from '../services/createCustomer';
import { browserHistory } from 'dva/router';
import { message } from 'antd';

export default {
  namespace: 'createCustomer',
  state: {
    operatorList: [],
    sellerList: [],
    validateRegiterCode: {
      status: '',
      help: ''
    }
  },
  reducers: {
    setRegisterCode(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    },
    setOperator (state, { payload }) {
      return {
        ...state,
        ...payload
      }
    },
    setSeller (state, { payload }) {
      return {
        ...state,
        ...payload
      }
    }
  },
  effects: {
    *fetchOperator({ payload }, { call, put }) {
      const { data } = yield call(createCustomerService.fetchOperator);
      if (data.success && data.data) {
        const result = data.data;
        yield put({
          type: 'setOperator',
          payload: {
            operatorList: result
          }
        })
      }
    },
    *fetchSeller({ payload }, { call, put }) {
      const { data } = yield call(createCustomerService.fetchSeller);
      if (data.success && data.data) {
        const result = data.data;
        console.log(result)
        yield put({
          type: 'setSeller',
          payload: {
            sellerList: result
          }
        })
      }
    },
    *submit({ payload }, { call, put }) {
      const { data } = yield call(createCustomerService.submit, { payload });
      if (data.success) {
        message.success('创建成功', 3);
        browserHistory.push('/page/manageCustomer');
        return;
      }
      message.error(data.msg || '系统错误，请重试', 3);
    },
    *removeRptCode({ payload }, { select, call, put }) {
      const { data } = yield call(createCustomerService.removeRptCode, { payload });
      if (data.success && data.data) {
        yield put ({
          type: 'setRegisterCode',
          payload: {validateRegiterCode: { status: 'success', help: '' }}
        });
        return;
      }
      yield put ({
        type: 'setRegisterCode',
        payload: {validateRegiterCode: { status: 'error', help: data.msg }}
      });
    }
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        if (pathname === '/page/createCustomer') {
          dispatch({
            type: 'fetchOperator'
          })
        }
      });
    }
  }
}
